package com.example.demo.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class UserAspect {
    @Pointcut("execution(* com.example.demo.controller.UserController.*(..))")
    public void pointcut(){
    }

    // 前置通知
    @Before("pointcut()")
    public void doBefore(){
        System.out.println("执行 Before 方法");
    }
    // 后置通知
    @After("pointcut()")
    public void doAfter(){
        System.out.println("执行 After 方法");
    }
    // return 之前通知
    @AfterReturning("pointcut()")
    public void doAfterReturning(){
        System.out.println("执行 AfterReturning 方法");
    }
    @AfterThrowing("pointcut()")
    public void doAfterThrowing(){
        System.out.println("执行 AfterThrowing 方法");
    }

    @Around("pointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint){
        Object obj = null;
        System.out.println("Around 方法开始执行");
        long startTime=System.currentTimeMillis();
        try {
            // 执行拦截方法
            obj = joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        System.out.println("Around 方法结束执行");
        long endTime=System.currentTimeMillis();
        float excTime=(float)(endTime-startTime)/1000;
        System.out.println("执行时间："+excTime+"s");
        return obj;
    }
}
